package com.ivanceras.client.widgets;

import com.ivanceras.shared.bo.Ad_column;
import com.ivanceras.shared.bo.Ad_field;
import com.ivanceras.shared.bo.Ad_tab;
import com.ivanceras.shared.db.Filter;

public class FilterManager {
	
	private AdTabUi[] tabUiList = null;
	private AdTabUi parentTabUi = null;
	
	public FilterManager(AdTabUi[] tabUiList){
		this.tabUiList = tabUiList;
	}
	
	public Filter getFilter(AdTabUi tabUi){
		//AdTabUi tabUi = tabList.get(tabIndex);
		Ad_tab adtab = tabUi.getAd_tab();
		Ad_column pcolumn = getParentColumn(adtab);
		Filter filter = null;
		System.out.println("Getting filter for this tab: "+tabUi.getAd_tab().getName()+" with column that match: "+(pcolumn != null ? pcolumn.getColumnname() : null));
		if(pcolumn != null){
			String columnName = pcolumn.getColumnname();
			int ptabIndex = getParentTabIndex(pcolumn);
			parentTabUi = tabUiList[ptabIndex];
			Object value = parentTabUi.getFieldValue(columnName);
			filter = new Filter(columnName.toLowerCase(), Filter.EQUAL, value);
			
			System.out.println("Filter will be: "+filter.toString());
		}
		return filter;
	}
	
	private int getParentTabIndex(Ad_column column){
		String columnName = column.getColumnname();
		for(int i = 0; i < tabUiList.length; i++){
			Ad_tab adtab = tabUiList[i].getAd_tab();
			Ad_field[] fieldList = adtab.getAd_fieldList();
			for(Ad_field f : fieldList){
				String fcolumn = f.getAd_column().getColumnname();
				if(columnName.equals(fcolumn)){
					return i;
				}
			}
		}
		return -1;
	}
	
	public AdTabUi getParentTabUi(){
		return parentTabUi;
	}
	
	private Ad_column getParentColumn(Ad_tab tab){
		Ad_field[] fieldList = tab.getAd_fieldList();
		for(Ad_field field : fieldList){
			Ad_column column = field.getAd_column();
			if(column.getIsparent().equals("Y")){
				return column;
			}
		}
		return null;
	}

}
